package portOperation;

import java.util.HashMap;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

public class httpPortPost {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
    public static String Post(String url, JSONObject json,HashMap<String, String> header) {
    	CloseableHttpClient httpclient = HttpClients.createDefault();
        //DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        String result = null;
        try {
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");
            post.setEntity(s);
            
			if (header.size() > 0) {
				for (HashMap.Entry<String, String> entry : header.entrySet()) {
					post.addHeader(entry.getKey(), entry.getValue());
				}
			}
            
		    CloseableHttpResponse res = httpclient.execute(post);
            //HttpResponse res = client.execute(post);
            int i = res.getStatusLine().getStatusCode();
            if (HttpStatus.SC_OK == i) {
                result = EntityUtils.toString(res.getEntity());
            } else {
            	result = "doPost errcode="+i;
            } 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
